import React, { Component } from 'react';
import { connect } from 'react-redux';

import { List, Badge } from 'antd-mobile';

class Msg extends Component {
    render() {
        const Item = List.Item;
        const Brief = Item.Brief;

        const { chatList, user, users } = this.props;
        const currentId = user._id;
        const chatGroup = {};
        chatList.toJS().forEach(item => {//通过chatid把聊天分组
            chatGroup[item.chatid] = chatGroup[item.chatid] || [];
            chatGroup[item.chatid].push(item);
        });
        const chatListVal = Object.values(chatGroup).sort((a, b) => {
            const a_last = this.getLastChat(a).create_time;
            const b_last = this.getLastChat(b).create_time;
            return b_last - a_last;
        });
        return <div>
            {
                chatListVal.map(v => {
                    const usersInfo = users.toJS();
                    const chatItem = this.getLastChat(v);
                    const targetId = v[0].from === currentId ? v[0].to : v[0].from;
                    const unRead = v.filter(i => !i.read && i.to === currentId).length;
                    if(!usersInfo[targetId]) {
                       return null; 
                    }
                    return (
                        <List key={chatItem._id}>
                            <Item
                                extra={<Badge text={unRead}></Badge>}
                                thumb={require(`../../statics/avatar/${usersInfo[targetId].avatar}.png`)}
                                arrow='horizontal'
                                onClick={() => {
                                    this.props.history.push(`/chat/${targetId}`);
                                }}
                            >
                                {usersInfo[targetId].name}
                                <Brief>
                                    {chatItem.content}
                                </Brief>
                            </Item>
                        </List>
                    )
                })
            }
        </div>
    }
    
    getLastChat(array) { //获取最后一条聊天信息
        return array[array.length - 1];
    }
}

const mapStateToProps = (state) => ({
    user: state.getIn(['user', 'user']),
    chatList: state.getIn(['chat', 'chatList']),
    users: state.getIn(['chat', 'users'])
})

export default connect(mapStateToProps, null)(Msg);